/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pro.dao;

/**
 *
 * @author Cyndi
 */
import pro.dao.*;
import pro.bean.*;
import java.sql.*;
/**
 *
 * @author Niko
 */
public class PuntoDAO extends Dbase{
    
    public void registrarPunto(Punto punto) throws SQLException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb");
            conn.setAutoCommit(false);
            String sql = "insert into puntos"
                    + " values (?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, nuevoId());
            pstmt.setString(2, punto.getNombre());
            pstmt.setFloat(3, punto.getLatitud());
            pstmt.setFloat(4, punto.getAltitud());
            pstmt.setBoolean(5, punto.isPrincipal());
            pstmt.setString(6, punto.getNotas());
            pstmt.executeUpdate();
            conn.commit();
        } finally {
            if (pstmt != null) {
                pstmt.close();
                pstmt = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }
        }
    }
    
    public Integer nuevoId() throws SQLException {
        this.init_mysql();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Integer nuevoId = null;
        try {

            conn.setAutoCommit(false);
            String sql = "SELECT (CASE WHEN max(idpuntos) IS NULL THEN 0 ELSE max(idpuntos) END) + 1 FROM puntos";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                nuevoId = rs.getInt(1);
                nuevoId = nuevoId == null ? 1 : nuevoId;
            }
        } finally {
            if (pstmt != null) {
                pstmt.close();
                pstmt = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }

        }
        return nuevoId;
    }  
    
}
